<!--
 * @Author: 陈伟 chenwei@duoliheng.com
 * @Date: 2022-11-14 20:15:55
 * @LastEditors: 陈伟 chenwei@duoliheng.com
 * @LastEditTime: 2023-01-10 11:16:43
 * @FilePath: \cool.front\src\views\distributionManage\distributionTrack\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 配送员轨迹 -->
  <div v-loading="loading" class="main">
    <div class="name-box"><el-checkbox v-model="showName">显示名称</el-checkbox></div>
    <baidu-map
      id="SGbaidumap"
      class="map"
      :center="center"
      :zoom="zoom"
      :scroll-wheel-zoom="true"
      @ready="handler"
    >
      <!-- <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_RIGHT" /> -->
      <bm-scale anchor="BMAP_ANCHOR_BOTTOM_LEFT" />
      <div v-show="run === 1">
        <bm-marker v-for="(item,index) in gasmanOrder1" :key="index" :position="{lng: item.lon, lat: item.lat}" @click="look(item)">
          <bm-label
            :content="index + 1 + ''"
            :label-style="labelStyle"
            :offset="{width: 2, height: 2}"
          />
        </bm-marker>
        <bm-polyline :path="lineList" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="2" />
        <bml-lushu
          :path="lineList"
          :icon="icon"
          :play="play"
          :speed="200"
        />
      </div>
      <!-- 普通点 -->
      <div v-show="run === 4" v-if="markerList.length > 0&&!quick">
        <my-Overlay
          v-for="(item,index) in markerList"
          :key="index"
          :position="{lng: item.lon, lat: item.lat}"
          :color="item.color"
          :text="item.num"
          :info="item"
          @overlayClick="overlayClick"
        />
      </div>
      <!-- 海量点 -->
      <template v-if="points.length > 0&&quick">
        <div v-for="(item,index) in points" v-show="run === 4" :key="index">
          <bm-point-collection :points="item.pointsList" shape="BMAP_POINT_SHAPE_CIRCLE" :color="item.color" size="BMAP_POINT_SIZE_NORMAL" />
        </div>
      </template>

      <!-- 订单信息 -->
      <bm-info-window :position="position02" :auto-pan="false" :show="show02" @close="infoWindowClose" @open="infoWindowOpen">
        <el-descriptions :column="1" :v-model="from">
          <el-descriptions-item label="订单号">{{ from.orderCode }}</el-descriptions-item>
          <el-descriptions-item label="客户编号">{{ from.csmCode }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ from.contact }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ from.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ from.csmAddress }}</el-descriptions-item>
          <el-descriptions-item label="站点">{{ from.orgName }}</el-descriptions-item>
          <el-descriptions-item label="配送距离">{{ distanceFormat(from.distance) }}km</el-descriptions-item>
          <el-descriptions-item label="配送员编号">{{ from.ownerCode }}</el-descriptions-item>
          <el-descriptions-item label="配送员">{{ from.ownerName }}</el-descriptions-item>
          <el-descriptions-item label="商品描述">{{ from.goodsDesc }}</el-descriptions-item>
          <el-descriptions-item label="签收时间">{{ from.signDt?parseTime(from.signDt, '{y}-{m}-{d} {h}:{i}:{s}'):'' }}</el-descriptions-item>
        </el-descriptions>
      </bm-info-window>
      <template v-if="showName">
        <template v-if="fenceData.length">
          <!-- <bm-marker v-for="(item,index) in tableData" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false"> -->
          <bm-label v-for="item in fenceData" :key="item.id" :position="{lng: item.longitude, lat: item.latitude}" :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'blue', fontSize : '14px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
          <!-- </bm-marker> -->
        </template>
        <template v-if="fenceData1.length">
          <!-- <bm-marker v-for="(item,index) in tableData1" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false"> -->
          <bm-label v-for="item in fenceData1" :key="item.id" :position="{lng: item.longitude, lat: item.latitude}" :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'red', fontSize : '12px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
          <!-- </bm-marker> -->
        </template>
      </template>
    </baidu-map>

    <div ref="right" class="right">
      <i class="el-icon-d-arrow-right" @click="fold('right')" />
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="配送员列表" name="1">
          <el-card class="rightCard">
            <el-form ref="form" :model="submit" label-width="80px" style="padding: 5px;">
              <el-form-item class="merge-item" label="查询日期:">
                <el-date-picker
                  v-model="submit.signDate1"
                  type="date"
                  :clearable="false"
                  placeholder="选择日期时间"
                />
              </el-form-item>
              <el-form-item label="组织机构:" prop="orgSNNo">
                <el-tree-select
                  v-model="submit.orgSNNo1"
                  clearable
                  class="tree-select"
                  :popover-width="360"
                  :select-params="{
                    clearable: true,
                    placeholder: '请选择',
                    loading: $loadingPlugin.getTreeData
                  }"
                  :tree-params=" {
                    'expand-on-click-node': false,
                    'highlight-current': true,
                    props:{
                      value:'orgSNNo',
                      label: 'orgName',
                      disabled: 'disabled',
                    },
                    data: treeData
                  }"
                  @node-click="selectTreeChange1"
                />
              </el-form-item>
              <el-form-item :table-form-merge="0.2">
                <el-checkbox v-model="submit.option1" label="包含下级" />
              </el-form-item>
              <el-form-item label="">
                <!-- <el-input v-model.trim="submit.userName" style="width: 120px;" /> -->
                <el-button v-permission="[50103, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
              </el-form-item>
              <el-table ref="table1" v-loading="loadingShow" height="590px" :data="tableData1" border element-loading-text="加载中" highlight-current-row @selection-change="handleSelectionChange">
                <el-table-column type="index" label="#" width="50" align="center" />
                <el-table-column type="selection" width="50" align="center" :selectable="(row,index)=>{return row.orderCount>0}" />
                <el-table-column prop="userName" label="姓名" align="center">
                  <template slot-scope="scoped">
                    <span :style="{color:scoped.row.color}">{{ scoped.row.userName }}({{ scoped.row.orderCount }}单)</span>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="颜色" width="80" align="center" class-name="color-column">
                  <template slot-scope="scoped">
                    <colorPicker v-if="scoped.row.color" v-model="scoped.row.color" @change="changeFillColor(scoped.row.color,scoped.row.userId)" />
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="站点列表" name="2">
          <el-card class="rightCard">
            <el-form ref="form" :model="submit" label-width="80px" style="padding: 5px;">
              <el-form-item class="merge-item" label="查询日期:">
                <el-date-picker
                  v-model="submit.signDate2"
                  type="date"
                  :clearable="false"
                  placeholder="选择日期时间"
                />
                <el-button v-permission="[50103, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
                <el-button type="success" icon="el-icon-position" @click="openQuick(quick)">{{ quick?'关闭':'开启' }}极速模式</el-button>
              </el-form-item>
              <el-table v-loading="loadingShow" height="720px" :data="tableData2" element-loading-text="加载中" border highlight-current-row @selection-change="handleSelectionChange">
                <el-table-column type="index" label="#" width="50" align="center" />
                <el-table-column type="selection" width="50" align="center" :selectable="(row,index)=>{return row.orderCount>0}" />
                <el-table-column prop="userName" label="站点名称" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="scoped">
                    <span :style="{color:scoped.row.color}">{{ scoped.row.orgName }}({{ scoped.row.orderCount }}单)</span>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="颜色" width="80" align="center" class-name="color-column">
                  <template slot-scope="scoped">
                    <colorPicker v-if="scoped.row.color" v-model="scoped.row.color" @change="changeFillColor(scoped.row.color,scoped.row.orgId)" />
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="配送员轨迹" name="3">
          <el-card class="rightCard">
            <el-form ref="form" :model="submit" label-width="80px" style="padding: 5px;">
              <el-form-item class="merge-item" label="查询日期:">
                <el-date-picker
                  v-model="submit.signDate3"
                  type="date"
                  :clearable="false"
                  placeholder="选择日期时间"
                />
              </el-form-item>
              <el-form-item label="组织机构:" prop="orgSNNo">
                <el-tree-select
                  v-model="submit.orgSNNo3"
                  clearable
                  class="tree-select"
                  :popover-width="360"
                  :select-params="{
                    clearable: true,
                    placeholder: '请选择',
                    loading: $loadingPlugin.getTreeData
                  }"
                  :tree-params=" {
                    'expand-on-click-node': false,
                    'highlight-current': true,
                    props:{
                      value:'orgSNNo',
                      label: 'orgName',
                      disabled: 'disabled',
                    },
                    data: treeData
                  }"
                  @node-click="selectTreeChange3"
                />
              </el-form-item>
              <el-form-item :table-form-merge="0.2">
                <el-checkbox v-model="submit.option3" label="包含下级" />
              </el-form-item>
              <el-form-item label="姓名:">
                <el-input v-model.trim="submit.userName" style="width: 120px;" />
                <el-button v-permission="[50103, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
              </el-form-item>
              <lb-table
                ref="lbTable"
                v-el-height-adaptive-table="{bottomOffset:10}"
                class="table01"
                style="height: 590px;"
                border
                highlight-current-row
                element-loading-text="加载中"
                :column="tableData.column"
                :data="tableData.data"
                :total="tableData.total"
                custom-column
                @row-click="handleCurrentChange1"
              />
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>
      <!-- 配送单 -->
      <el-collapse v-show="run === 1 && gasmanOrder1.length > 0" class="orderListPage" :value=" gasmanOrder1.length>0 ? 1 : 0">
        <el-collapse-item :title="` 共找到${gasmanOrder1.length}个结果`" :name="1">
          <lb-table
            ref="lbTable"
            class="table02"
            border
            element-loading-text="加载中"
            :column="tableData02.column"
            :data="tableData02.data"
            :total="tableData02.total"
            custom-column
            max-height="345"
            style="overflow: auto;"
            @current-change="handleCurrentChange"
          />
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  // import dayjs from 'dayjs'
  import { parseTime } from '@/utils'
  import { BmlLushu } from 'vue-baidu-map'
  import { companySetting, trackAllgasman, trackGasmanOrder, trackTrackRectify, selectUserFence, selectOrgFence, queryAllgasman, queryByUserIds, queryByOrgIds } from '@/api'
  import myOverlay from '../components/myOverlay.vue'
  // import { minDate } from '@/utils/config'
  export default {
    name: 'distributionTrack',
    components: {
      BmlLushu,
      myOverlay
    },
    data() {
      return {
        showName: true,
        quick: false,
        points: [],
        loading: false,
        activeName: '1',
        fenceData: [], // 站点围栏
        fenceData1: [], // 配送员围栏
        orderList: [], // 订单数据
        markerList: [], // 点集合
        orgId: null,
        labelStyle: { color: '#fff', fontSize: '12px', background: 'rgba(0, 0, 0, 0)', borderColor: 'rgba(0, 0, 0, 0)' },
        play: true,
        title: 15,
        icon: {
          url: require('../../../assets/map_images/gasman2.png'),
          // url: 'http://api.map.baidu.com/library/LuShu/1.2/examples/car.png',
          size: { width: 40, height: 45 },
          opts: { anchor: { width: 10, height: 13 }}
        },
        submit: {
          userName: null,
          signDate1: new Date(),
          signDate2: new Date(),
          signDate3: new Date(),
          orgSNNo1: null,
          orgSNNo3: null,
          option1: false,
          option3: false
        },
        show: false,
        run: 2,
        show02: false,
        from: {},
        position: { lng: 0, lat: 0 },
        position02: { lng: 0, lat: 0 },
        center: { lng: 0, lat: 0 },
        lineList: [],
        zoom: 14,
        BMap: {},
        map: null,
        txt: '',
        ids: [],
        qtype: 1,
        treeData: [],
        query: {},
        tableData1: [],
        tableData2: [],
        loadingShow: false,
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              align: 'center',
              width: 50
            },
            {
              prop: 'userName',
              label: '姓名',
              showOverflowTooltip: true,
              render: (h, { row }) =>
              <div onClick={() => this.getlocation(row)} style={row.color ? `color:${row.color}` : ''}>
                {row.userName}（{row.orderCount}单）
              </div>
            }, {
              prop: '',
              label: '异常',
              render: (h, { row }) =>
              <div style={row.intSpare6 >> 18 & 0x01 === 1 ? 'color:red' : ''}>
                {row.intSpare6 >> 18 & 0x01 === 1 ? '异常' : ''}
              </div>
            }
          ],
          data: []
        },
        tableData02: {
          total: 0,
          column: [
            {
              type: 'index',
              align: 'center',
              width: 30
            },
            {
              label: '',
              align: 'left',
              render: (h, { row }) =>
              <div class='tableInfo' style={row.intSpare6 >> 18 & 0x01 === 1 ? 'color:red' : ''}>
                <div style=' white-space: normal !important;'>{row.csmAddress}</div>
                <div style=' white-space: normal !important;'>{row.signDt ? parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}:{s}') : ''}</div>
              </div>
            }
          ],
          data: []
        },
        // 配送员订单
        gasmanOrder1: [],
        // 轨迹
        trackRectify1: []
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo'
      ])
    },
    watch: {
      'submit.orgSNNo1': {
        handler(newName, oldName) {
          console.log(newName)
          if (!newName) this.orgId = null
        },
        immediate: true
      },
      'submit.orgSNNo3': {
        handler(newName, oldName) {
          console.log(newName)
          if (!newName) this.orgId = null
        },
        immediate: true
      }
    },
    created() {
      this.getTreeData()
      this.search()
    },
    mounted() {

    },
    methods: {
      parseTime,
      async handler({ BMap, map }) {
        const _this = this
        this.zoom = 15
        this.BMap = BMap
        this.map = map
        const res = await companySetting()
        let currentCity = ''
        if (res.data.rows && res.data.rows.length > 0 && res.data.rows[0].city && res.data.rows[0].city !== '') currentCity = res.data.rows[0].city
        if (currentCity !== '') {
          map.centerAndZoom(currentCity, 14)
        } else {
          const localCity = new BMap.LocalCity()
          localCity.get(function(result) {
            const cityName = result.name
            map.centerAndZoom(cityName, _this.zoom)
          })
        }
      },
      // 切换标签页
      async handleClick(val) {
        this.quick = false
        // 切换站点先清除地图展示的围栏
        this.markerList = []
        this.run = 2
        this.orgSNNo = null
        this.orgId = null
        if (this.map) {
          this.map.clearOverlays()
        }

        // if (this.fenceData.length > 0) {
        // await this.fenceData.forEach(item => {
        //     this.map.removeOverlay(item.polygon)
        //   })
        // }
        // if (this.fenceData1.length > 0) {
        //  await this.fenceData1.forEach(item => {
        //     this.map.removeOverlay(item.polygon)
        //   })
        // }
        if (this.activeName === '1') {
          this.getGasmanList()
          if (this.orgId) {
            this.chooseOrg(this.orgId)
          }
        }
        if (this.activeName === '2') {
          // this.tableData2.data = res.data
          this.getAllgasman()
          this.getData()
        }
        if (this.activeName === '3') {
          const params = {
            signDate: this.submit.signDate3,
            orgSNNo: this.submit.orgSNNo3,
            userName: this.submit.userName
          }
          const res = await trackAllgasman(params)
          if (res.data) { this.tableData.data = res.data }
          if (this.orgId) {
            this.chooseOrg(this.orgId)
          }
        }
      },
      currentRow(row) {

      },
      handleCurrentChangeOne() {

      },
      // 勾选
      async handleSelectionChange(val) {
        // console.log(val)
        if (val.length === 0) {
          this.markerList = []
          this.points = []
          // this.map.clearOverlays()
          this.loading = false
          return
        }
        if (this.activeName === '1') {
          // 匹配和配送员相同的订单
          const list = await this.orderList.filter(item => val.some(ele => ele.userId === item.ownerId))
          // console.log(list)
          this.$nextTick(() => {
            this.markerList = list
          })
          if (list.length > 0) {
            // eslint-disable-next-line no-undef
            this.map.centerAndZoom(new BMap.Point(list[0].lon, list[0].lat), 15)
            this.run = 4
            this.loading = false
          }
        }
        if (this.activeName === '2') {
          // 匹配和站点相同的订单
          const list = await this.orderList.filter(item => val.some(ele => ele.orgId === item.orgId))
          // console.log(list)
          const box = []
          await val.forEach(item => {
            box.push({ pointsList: item.points, color: item.color, orgId: item.orgId })
          })
          console.log('box', box)
          this.$nextTick(() => {
            this.points = box
            this.markerList = list
          })
          if (list.length > 0) {
            // eslint-disable-next-line no-undef
            this.map.centerAndZoom(new BMap.Point(list[0].lon, list[0].lat), 15)
            this.run = 4
            this.loading = false
          }
        }
        if (this.activeName === '3') {
          // this.tableData.data = res.data
        }
      },
      // 搜索
      async search() {
        if (this.map) {
          this.map.clearOverlays()
        }
        if (this.activeName === '1') {
          this.getGasmanList()
          if (this.orgId) {
            this.chooseOrg(this.orgId)
          }
        }
        if (this.activeName === '2') {
          this.getAllgasman()
          this.getData()
        }
        if (this.activeName === '3') {
          const params = {
            signDate: this.submit.signDate3,
            orgSNNo: this.submit.orgSNNo3,
            orgId: this.submit.option3 ? 0 : this.orgId,
            userName: this.submit.userName
          }
          const res = await trackAllgasman(params)
          this.tableData.data = res.data
          if (this.orgId) {
            this.chooseOrg(this.orgId)
          }
        }
      },
      // 开启极速模式
      openQuick(val) {
        // if(this.quick){
        //   this.quick = !this.quick
        //   return
        // }
        this.$confirm(`确认${this.quick ? '关闭' : '开启'}极速模式,${this.quick ? '关闭极速模式后需要重新勾选数据' : '开启极速模式后需要重新勾选数据,且无法展示单个订单数据'}`, '提示', {
          type: 'warning'
        }).then(() => {
          this.markerList = []
          this.points = []
          this.quick = !this.quick
        }).catch(() => {
          this.$message.info('已取消')
        })
      },
      // 更改填充颜色
      async changeFillColor(value, id) {
        // console.log(value,id)
        if (this.activeName === '1') {
          await this.orderList.forEach((item, index) => {
            if (id === item.ownerId) {
              item.color = value
            }
          })
        }
        if (this.activeName === '2') {
          await this.orderList.forEach((item, index) => {
            if (id === item.orgId) {
              item.color = value
            }
          })
          await this.points.forEach(item => {
            if (id === item.orgId) {
              item.color = value
            }
          })
        }
      },
      // 获取配送员列表
      async getGasmanList() {
        this.loadingShow = true
        const params = {
          signDate: this.submit.signDate1,
          orgSNNo: this.submit.orgSNNo1,
          orgId: this.submit.option1 ? 0 : this.orgId
        }
        const res = await trackAllgasman(params)
        this.tableData1 = res.data
        const userIdsStr = []
        await this.tableData1.forEach((item, index) => {
          item.num = index + 1
          userIdsStr.push(item.userId + '=' + item.color)
        })
        if (!userIdsStr.length) {
          this.loadingShow = false
          return
        }
        const res1 = await queryByUserIds({ userIdsStr: String(userIdsStr), date: parseTime(params.signDate, '{y}-{m}-{d} {h}:{i}:{s}') })
        this.orderList = res1.data
        await this.tableData1.forEach(item => {
          // this.$nextTick(()=>{
          //   this.$refs.table1.toggleRowSelection(item, item.orderCount>0)
          // })
          this.orderList.forEach(e => {
            if (item.userId === e.ownerId) {
              // 订单点上加编号
              e.num = String(item.num)
            }
          })
        })
        this.loadingShow = false
        // console.log('tableData1',this.tableData1)
        // console.log('orderList',this.orderList)
      },
      // 获取全部站点围栏
      async getData() {
        const res = await selectOrgFence()
        this.fenceData = []
        this.fenceData1 = []
        this.fenceData = res.data.map(item => {
          item.showDetail = false
          if (item.coordinates) {
            item.path = JSON.parse(item.coordinates)
            const options = {
              strokeColor: item.borderColor, // 边线颜色。
              fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
              strokeWeight: 5, // 边线的宽度，以像素为单位。
              strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
              fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
              strokeStyle: 'dashed' // 边线的样式，solid或dashed。
            }
            const ps = []
            for (var i in item.path) {
              // eslint-disable-next-line no-undef
              ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
            }
            // eslint-disable-next-line no-undef
            const polygon = new BMap.Polygon(ps, options) // 创建多边形
            item.polygon = polygon
            this.map.addOverlay(polygon)
          }
          return {
            position: {
              lng: item.lon, lat: item.lat
            },
            ...item
          }
        })
      },
      // 选择所属机构查站点围栏和下面的子围栏
      selectTreeChange1(value) {
        this.orgSNNo = value.orgSNNo
        this.orgId = value.orgId
      },
      selectTreeChange3(value) {
        this.orgSNNo = value.orgSNNo
        this.orgId = value.orgId
      },
      // 获取站点列表数据
      async getAllgasman() {
        this.loadingShow = true
        const res = await queryAllgasman({})
        //  queryByOrgIds
        if (res.data) {
          const list = res.data
          const orgIdsStr = []
          let list1 = []
          const colorList = []
          await list.forEach((item, index) => {
            item.orderCount = 0
            item.num = index + 1
            orgIdsStr.push(item.orgId + '=' + item.color)
            colorList.push(item.color)
          })
          const res1 = await queryByOrgIds({ orgIdsStr: String(orgIdsStr), date: parseTime(this.submit.signDate2, '{y}-{m}-{d} {h}:{i}:{s}') })
          list1 = res1.data
          await list.forEach(item => {
            const points = []
            list1.forEach(e => {
              if (e.orgId === item.orgId) {
                // 订单点上加编号
                e.num = String(item.num)
                item.orderCount++
                // 同一站点的订单，放在一起
                points.push({ lng: e.lon, lat: e.lat })
                item.points = points
              }
            })
          })
          // 订单数为了0的站点没有颜色
          let num = -1
          await list.forEach(item => {
            if (!item.orderCount) {
              item.color = ''
            } else {
              num++
              item.color = colorList[num]
            }
          })
          // 改变订单列表的订单颜色
          await list.forEach(item => {
            list1.forEach(e => {
              if (e.orgId === item.orgId) {
                e.color = item.color
              }
            })
          })
          this.orderList = list1
          // console.log(this.orderList)
          this.tableData2 = list
          this.loadingShow = false
        // console.log(this.tableData2)
        }
      },
      // 选中站点
      async chooseOrg(value) {
        this.chooseOrgId = value
        // 查询站点围栏和下面的子围栏
        await selectUserFence({ orgId: value }).then(res => {
          if (res.data) {
            this.fenceData = []
            this.fenceData1 = []
            this.fenceData = res.data.filter(item => {
              if (item.fenceType === 1) {
                item.showDetail = false
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
            this.fenceData1 = res.data.filter(item => {
              if (item.fenceType === 2) {
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                item.isOpen = item.isOpen === 1
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
          // console.log(this.fenceData)
          // console.log(this.fenceData1)
          }
        }).catch(err => {
          console.log(err)
          this.fenceData = []
          this.fenceData1 = []
        })
      },
      infoWindowClose() {
        this.show02 = false
      },
      infoWindowOpen() {
        this.show02 = true
      },
      // 折叠效果
      fold(refItem) {
        console.log(this.$refs[refItem].childNodes)
        const classname = event.target.className
        const flag = classname.includes('right')
        if (flag) {
          event.target.className = 'el-icon-d-arrow-left'
        } else {
          event.target.className = 'el-icon-d-arrow-right'
        }
        var width = this.$refs[refItem].style.width
        if (width === '20px') {
          this.$refs[refItem].style.width = '500px'
          this.$refs[refItem].childNodes[2].style.display = 'block'
          // this.$refs[refItem].childNodes[4].style.display = 'block'
        } else {
          this.$refs[refItem].style.width = '20px'
          this.$refs[refItem].childNodes[2].style.display = 'none'
          this.$refs[refItem].childNodes[4].style.display = 'none'
        }
      },
      // 点击图标
      look(item) {
        this.from = item
        // item.distance
        this.content = item.name
        this.position02.lng = item.lon
        this.position02.lat = item.lat
        this.show02 = true
      },
      distanceFormat(v, r, i) {
        if (!Number(v)) {
          return ''
        }
        var msg = (Number(v) / 1000 || 0).toFixed(2)
        return msg
      },
      getlocation(row) {
        if (!row) {
          this.$message({
            message: '没有查询到相关数据',
            type: 'warning'
          })
        } else {
          this.position.lat = row.lat
          this.position.lng = row.lon
          this.center = this.position
          this.show = true
          this.run = 1
        }
      },
      // 配送轨迹选中
      async handleCurrentChange1(row) {
        // this.map.clearOverlays()
        const params = {
          date: parseTime(this.submit.signDate3, '{y}-{m}-{d} {h}:{i}:{s}'),
          // date: (this.submit.signDate*1/1000).toString(),
          userId: row.userId
        }
        const res = await trackGasmanOrder(params)
        this.gasmanOrder1 = []
        this.tableData02.data = []
        await this.trackRectify()
        const list = res.data.rows
        const box = list.filter(item => (!(!item.lon || !item.lat || item.lon < 0 || item.lon > 180 || item.lat < 0 || item.lat > 180 || item.lon === 4.9E-324 || item.lat === 4.9E-324)))
        // console.log('box',box)
        this.gasmanOrder1 = box.reverse()
        if (this.gasmanOrder1.length === 0) this.$message.info('没有查询到相关数据')
        this.tableData02.data = box
        await this.trackRectify(box)
        // console.log('gasmanOrder1',this.gasmanOrder1)
        // console.log('tableData02',this.tableData02)
      },
      async trackRectify(orderList, callback) {
        if (!orderList || orderList.length === 0) {
          return
        }
        orderList.reverse()
        var array = []
        var firstLocateTime = 0
        for (var i = 0; i < orderList.length; i++) {
          var p = orderList[i]
          if (!p || !p.lon || !p.lat || p.lon < 0 || p.lon > 180 || p.lat < 0 || p.lat > 180 || p.lon === 4.9E-324 || p.lat === 4.9E-324) {
            continue
          }
          //
          if (firstLocateTime === 0) {
            firstLocateTime = this.parseDate(p.signDt).getTime()
          } else {
            firstLocateTime += 3 * 60 * 1000
          }
          var time = '' + firstLocateTime
          time = time.substring(0, time.length - 3)

          array.push({
            latitude: p.lat,
            longitude: p.lon,
            coord_type_input: 'bd09ll',
            loc_time: time,
            // speed: 10,
            radius: 7
          })
        }
        const params = {
          pointList: array,
          transport_mode: 'riding'
        }
        const rlt = await trackTrackRectify(params)
        this.lineList = []
        if (rlt) {
          console.log('纠偏结果', rlt)
          array = []
          JSON.parse(rlt.data).forEach(function(p) {
            // eslint-disable-next-line no-undef
            var point = new BMap.Point(p.longitude, p.latitude)
            array.push(point)
          })
          this.trackRectify1 = JSON.parse(rlt.data)
          this.poly()
        }
      },
      parseDate(str) {
        if (/^([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,3})\+(0800)$/.test(str)) {
          return new Date(str)
        }
        str = String(str).replace(/-/g, '/').replace('Z', '').replace('T', ' ')
        if (str.indexOf('.') > 0) {
          var dd = str.split('.')
          var d = new Date(dd[0])
          d.setMilliseconds(dd[1])
          return d
        }
        return new Date(str)
      },
      // 获取所属机构数据
      async getTreeData() {
        // const res = await organizationQueryList({})
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.submit.orgSNNo1 = this.userInfo.orgSNNo
        this.orgId = this.userInfo.orgId
      },
      // 折线
      poly() {
        var newArr = JSON.parse(JSON.stringify(this.trackRectify1))

        for (let i = 0; i < newArr.length; i++) {
          if (i === 0) {
            // eslint-disable-next-line no-undef
            var point = new BMap.Point(newArr[0].longitude, newArr[0].latitude)
            // console.log(this.map)
            this.map.centerAndZoom(point, 20)
          }
          var objArr = []
          objArr.lng = newArr[i].longitude
          objArr.lat = newArr[i].latitude
          this.lineList.push(objArr)
        }
      },
      // 获取选中
      handleCurrentChange(val) {
        this.position02.lat = val.lat
        this.position02.lng = val.lon
        // eslint-disable-next-line no-undef
        var point = new BMap.Point(val.lon, val.lat)
        // console.log(this.map)
        this.map.centerAndZoom(point, 20)
        this.show02 = true
        this.from = val
      },
      overlayClick(val) {
        this.position02.lat = val.lat
        this.position02.lng = val.lon
        // eslint-disable-next-line no-undef
        var point = new BMap.Point(val.lon, val.lat)
        // console.log(this.map)
        this.map.centerAndZoom(point, 20)
        this.show02 = true
        this.from = val
      }
    }
  }
</script>

<style lang='scss' scoped>
.main {
  position: relative;
  display: flex;
  height: 100%;
  font-size: 14px;
  .name-box {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 1200;
  }
  /deep/ .el-table .el-table__body tr {
    cursor: pointer;
  }
  .el-form-item {
    margin-bottom: 10px;
  }
  .tableInfo {
    font-size: 14px;
    font-weight: 500;
  }
  .map {
    position: relative;
    width: 100%;
    height: 100%;
    // .bmLabel{
    //   background-color: transparent;
    //   color: black;
    //   font-weight: 700;
    //   font-size: 16px;
    //   border: 0;
    // }
    .label-style {
      font-size: 12px;
      color: #fff;
      background: rgba(0, 0, 0, 0);
      border-color: rgba(0, 0, 0, 0);
    }

    /deep/ .el-descriptions-item__label {
      width: 70px;
    }
  }

  .right {
    position: relative;
    width: 500px;
    height: 100%;
    padding: 4px;
    font-size: 14px;
    // font-weight: bold;
    // color: #777;
    transition: all 0.3s;
    /deep/ .el-collapse-item__header {
      text-indent: 5px;
    }
    i {
      position: absolute;
      top: 3px;
      right: 0;
      z-index: 100;
      cursor: pointer;
    }
    .el-table {
      overflow-y: auto;
      color: #DCDCDC;
      /deep/ .color-column {
        .cell {
          overflow: visible;
          .open {
            right: 0;
          }
        }
      }
    }
    .table01 /deep/.el-table {
      color: #DCDCDC;
    }
    .orderListPage {
      position: absolute;
      top: 70px;
      left: -240px;
      z-index: 100;
      width: 240px;
      height: 400px;
      transition: all 0.3s;

      i {
        position: absolute;
        top: 13px;
        right: 0;
      }

      .listTop {
        height: 40px;
        line-height: 40px;
        background-color: #fff;
      }

      /deep/ .el-card__body {
        padding: 0;
      }
      .table02 {
        height: 350px;
      }
    }

    .rightCard {
      height: calc(100% - 27px);

      /deep/ .el-card__body {
        padding: 0;
      }
      /deep/ .el-card__header {
        height: 24px;
        padding: 0 10px;
        font-size: 14px;
        font-weight: bold;
        // padding: 0;
        line-height: 24px;
        color: #373A3C;
        background: #e3e3e3;
        border: 1px solid #ddd;
        box-sizing: border-box;
      }
    }
  }
}
#SGbaidumap {
  /*
  去除百度地图版权
  去除右上角[地图、卫星、三维]控件
  去除百度地图右上角平移缩放控件的市县区文字
  */
  >>> .anchorBL,
  >>> .anchorTR,
  >>> .BMap_zlHolder,
  >>> [id^=PanoramaFlashWraperTANGRAM] {
    display: none;
    visibility: hidden;
  }
}
</style>
